<?php
namespace app\api\controller;

use think\Db;
use think\Exception;

class Statistics extends BaseController
{
    /**
     * 获取用户统计数据
     */
    public function getUserStats()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        
        try {
            // 订单统计
            $order_stats = [
                'total_orders' => Db::name('orders')->where('member_id', $member_id)->count(),
                'completed_orders' => Db::name('orders')->where(['member_id' => $member_id, 'status' => 'completed'])->count(),
                'cancelled_orders' => Db::name('orders')->where(['member_id' => $member_id, 'status' => 'cancelled'])->count(),
                'total_amount' => Db::name('orders')->where(['member_id' => $member_id, 'status' => 'completed'])->sum('total_amount') ?: 0
            ];
            
            // 停车统计
            $parking_stats = [
                'total_parking' => Db::name('parking_records')->where('member_id', $member_id)->count(),
                'total_parking_time' => Db::name('parking_records')->where('member_id', $member_id)->sum('parking_duration') ?: 0,
                'total_parking_fee' => Db::name('parking_records')->where('member_id', $member_id)->sum('parking_fee') ?: 0,
                'monthly_parking' => Db::name('monthly_parking')->where(['member_id' => $member_id, 'status' => 'active'])->count()
            ];
            
            // 优惠券统计
            $coupon_stats = [
                'total_coupons' => Db::name('member_coupons')->where('member_id', $member_id)->count(),
                'used_coupons' => Db::name('member_coupons')->where(['member_id' => $member_id, 'status' => 'used'])->count(),
                'expired_coupons' => Db::name('member_coupons')->where(['member_id' => $member_id, 'status' => 'expired'])->count(),
                'available_coupons' => Db::name('member_coupons')->where(['member_id' => $member_id, 'status' => 'available'])->count()
            ];
            
            // 积分统计
            $points_stats = [
                'total_points' => 0, // 需要从数据库获取积分信息
                'earned_points' => Db::name('points_log')->where(['member_id' => $member_id, 'type' => 'earn'])->sum('points') ?: 0,
                'used_points' => Db::name('points_log')->where(['member_id' => $member_id, 'type' => 'use'])->sum('points') ?: 0
            ];
            
            // 活动统计
            $activity_stats = [
                'participated_activities' => Db::name('activity_participants')->where('member_id', $member_id)->count(),
                'won_activities' => Db::name('activity_participants')->where(['member_id' => $member_id, 'is_winner' => 1])->count()
            ];
            
            $result = [
                'order_stats' => $order_stats,
                'parking_stats' => $parking_stats,
                'coupon_stats' => $coupon_stats,
                'points_stats' => $points_stats,
                'activity_stats' => $activity_stats
            ];
            
            return $this->renderSuccess($result);
        } catch (Exception $e) {
            return $this->renderError('获取统计数据失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取停车记录统计
     */
    public function getParkingStats()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $period = input('period/s', 'month'); // week, month, year
        
        try {
            $where = ['member_id' => $member_id];
            
            // 根据时间段设置查询条件
            switch ($period) {
                case 'week':
                    $start_time = date('Y-m-d', strtotime('-7 days'));
                    break;
                case 'month':
                    $start_time = date('Y-m-d', strtotime('-30 days'));
                    break;
                case 'year':
                    $start_time = date('Y-m-d', strtotime('-365 days'));
                    break;
                default:
                    $start_time = date('Y-m-d', strtotime('-30 days'));
            }
            
            $where['entry_time'] = ['>=', $start_time];
            
            // 按日期分组统计
            $daily_stats = Db::name('parking_records')
                ->where($where)
                ->field('DATE(entry_time) as date, COUNT(*) as count, SUM(parking_fee) as total_fee, SUM(parking_duration) as total_duration')
                ->group('DATE(entry_time)')
                ->order('date asc')
                ->select();
            
            // 总计统计
            $total_stats = [
                'total_count' => Db::name('parking_records')->where($where)->count(),
                'total_fee' => Db::name('parking_records')->where($where)->sum('parking_fee') ?: 0,
                'total_duration' => Db::name('parking_records')->where($where)->sum('parking_duration') ?: 0,
                'avg_fee' => 0,
                'avg_duration' => 0
            ];
            
            if ($total_stats['total_count'] > 0) {
                $total_stats['avg_fee'] = round($total_stats['total_fee'] / $total_stats['total_count'], 2);
                $total_stats['avg_duration'] = round($total_stats['total_duration'] / $total_stats['total_count'], 2);
            }
            
            $result = [
                'period' => $period,
                'daily_stats' => $daily_stats,
                'total_stats' => $total_stats
            ];
            
            return $this->renderSuccess($result);
        } catch (Exception $e) {
            return $this->renderError('获取停车统计失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取消费统计
     */
    public function getConsumptionStats()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $period = input('period/s', 'month');
        
        try {
            $where = ['member_id' => $member_id, 'status' => 'completed'];
            
            // 根据时间段设置查询条件
            switch ($period) {
                case 'week':
                    $start_time = date('Y-m-d', strtotime('-7 days'));
                    break;
                case 'month':
                    $start_time = date('Y-m-d', strtotime('-30 days'));
                    break;
                case 'year':
                    $start_time = date('Y-m-d', strtotime('-365 days'));
                    break;
                default:
                    $start_time = date('Y-m-d', strtotime('-30 days'));
            }
            
            $where['created_at'] = ['>=', $start_time];
            
            // 按日期分组统计
            $daily_stats = Db::name('orders')
                ->where($where)
                ->field('DATE(created_at) as date, COUNT(*) as count, SUM(total_amount) as total_amount')
                ->group('DATE(created_at)')
                ->order('date asc')
                ->select();
            
            // 按订单类型统计
            $type_stats = Db::name('orders')
                ->where($where)
                ->field('order_type, COUNT(*) as count, SUM(total_amount) as total_amount')
                ->group('order_type')
                ->select();
            
            // 总计统计
            $total_stats = [
                'total_orders' => Db::name('orders')->where($where)->count(),
                'total_amount' => Db::name('orders')->where($where)->sum('total_amount') ?: 0,
                'avg_amount' => 0
            ];
            
            if ($total_stats['total_orders'] > 0) {
                $total_stats['avg_amount'] = round($total_stats['total_amount'] / $total_stats['total_orders'], 2);
            }
            
            $result = [
                'period' => $period,
                'daily_stats' => $daily_stats,
                'type_stats' => $type_stats,
                'total_stats' => $total_stats
            ];
            
            return $this->renderSuccess($result);
        } catch (Exception $e) {
            return $this->renderError('获取消费统计失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取积分统计
     */
    public function getPointsStats()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $period = input('period/s', 'month');
        
        try {
            $where = ['member_id' => $member_id];
            
            // 根据时间段设置查询条件
            switch ($period) {
                case 'week':
                    $start_time = date('Y-m-d', strtotime('-7 days'));
                    break;
                case 'month':
                    $start_time = date('Y-m-d', strtotime('-30 days'));
                    break;
                case 'year':
                    $start_time = date('Y-m-d', strtotime('-365 days'));
                    break;
                default:
                    $start_time = date('Y-m-d', strtotime('-30 days'));
            }
            
            $where['created_at'] = ['>=', $start_time];
            
            // 按日期分组统计获得积分
            $daily_earn_stats = Db::name('points_log')
                ->where(array_merge($where, ['type' => 'earn']))
                ->field('DATE(created_at) as date, SUM(points) as points')
                ->group('DATE(created_at)')
                ->order('date asc')
                ->select();
            
            // 按日期分组统计使用积分
            $daily_use_stats = Db::name('points_log')
                ->where(array_merge($where, ['type' => 'use']))
                ->field('DATE(created_at) as date, SUM(points) as points')
                ->group('DATE(created_at)')
                ->order('date asc')
                ->select();
            
            // 按来源统计积分
            $source_stats = Db::name('points_log')
                ->where($where)
                ->field('source, type, SUM(points) as points')
                ->group('source, type')
                ->select();
            
            // 总计统计
            $total_stats = [
                'current_points' => 0, // 需要从数据库获取积分信息
                'earned_points' => Db::name('points_log')->where(array_merge($where, ['type' => 'earn']))->sum('points') ?: 0,
                'used_points' => Db::name('points_log')->where(array_merge($where, ['type' => 'use']))->sum('points') ?: 0,
                'total_earned' => Db::name('points_log')->where(['member_id' => $member_id, 'type' => 'earn'])->sum('points') ?: 0,
                'total_used' => Db::name('points_log')->where(['member_id' => $member_id, 'type' => 'use'])->sum('points') ?: 0
            ];
            
            $result = [
                'period' => $period,
                'daily_earn_stats' => $daily_earn_stats,
                'daily_use_stats' => $daily_use_stats,
                'source_stats' => $source_stats,
                'total_stats' => $total_stats
            ];
            
            return $this->renderSuccess($result);
        } catch (Exception $e) {
            return $this->renderError('获取积分统计失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取排行榜数据
     */
    public function getRankings()
    {
        $type = input('type/s', 'points'); // points, consumption, parking
        $period = input('period/s', 'month');
        $limit = input('limit/d', 10);
        
        try {
            $result = [];
            
            // 根据时间段设置查询条件
            switch ($period) {
                case 'week':
                    $start_time = date('Y-m-d', strtotime('-7 days'));
                    break;
                case 'month':
                    $start_time = date('Y-m-d', strtotime('-30 days'));
                    break;
                case 'year':
                    $start_time = date('Y-m-d', strtotime('-365 days'));
                    break;
                default:
                    $start_time = date('Y-m-d', strtotime('-30 days'));
            }
            
            switch ($type) {
                case 'points':
                    // 积分排行榜
                    $rankings = Db::name('points_log')
                        ->alias('pl')
                        ->leftJoin('members m', 'pl.member_id = m.member_id')
                        ->where([
                            'pl.type' => 'earn',
                            'pl.created_at' => ['>=', $start_time]
                        ])
                        ->field('pl.member_id, m.nickname, m.avatar, SUM(pl.points) as total_points')
                        ->group('pl.member_id')
                        ->order('total_points desc')
                        ->limit($limit)
                        ->select();
                    break;
                    
                case 'consumption':
                    // 消费排行榜
                    $rankings = Db::name('orders')
                        ->alias('o')
                        ->leftJoin('members m', 'o.member_id = m.member_id')
                        ->where([
                            'o.status' => 'completed',
                            'o.created_at' => ['>=', $start_time]
                        ])
                        ->field('o.member_id, m.nickname, m.avatar, SUM(o.total_amount) as total_amount')
                        ->group('o.member_id')
                        ->order('total_amount desc')
                        ->limit($limit)
                        ->select();
                    break;
                    
                case 'parking':
                    // 停车排行榜
                    $rankings = Db::name('parking_records')
                        ->alias('pr')
                        ->leftJoin('members m', 'pr.member_id = m.member_id')
                        ->where([
                            'pr.entry_time' => ['>=', $start_time]
                        ])
                        ->field('pr.member_id, m.nickname, m.avatar, COUNT(*) as parking_count, SUM(pr.parking_duration) as total_duration')
                        ->group('pr.member_id')
                        ->order('parking_count desc')
                        ->limit($limit)
                        ->select();
                    break;
                    
                default:
                    return $this->renderError('不支持的排行榜类型');
            }
            
            // 添加排名
            foreach ($rankings as $index => &$item) {
                $item['rank'] = $index + 1;
                $item['avatar'] = $item['avatar'] ? $this->getFullUrl($item['avatar']) : '';
            }
            
            $result = [
                'type' => $type,
                'period' => $period,
                'rankings' => $rankings
            ];
            
            return $this->renderSuccess($result);
        } catch (Exception $e) {
            return $this->renderError('获取排行榜失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取系统统计数据（管理员）
     */
    public function getSystemStats()
    {
        // 这里可以添加管理员权限验证
        
        try {
            // 用户统计
            $user_stats = [
                'total_users' => Db::name('members')->count(),
                'active_users' => Db::name('members')->where('status', 1)->count(),
                'new_users_today' => Db::name('members')->whereTime('created_at', 'today')->count(),
                'new_users_week' => Db::name('members')->whereTime('created_at', 'week')->count(),
                'new_users_month' => Db::name('members')->whereTime('created_at', 'month')->count()
            ];
            
            // 订单统计
            $order_stats = [
                'total_orders' => Db::name('orders')->count(),
                'completed_orders' => Db::name('orders')->where('status', 'completed')->count(),
                'pending_orders' => Db::name('orders')->where('status', 'pending')->count(),
                'cancelled_orders' => Db::name('orders')->where('status', 'cancelled')->count(),
                'total_revenue' => Db::name('orders')->where('status', 'completed')->sum('total_amount') ?: 0,
                'today_revenue' => Db::name('orders')->where('status', 'completed')->whereTime('created_at', 'today')->sum('total_amount') ?: 0
            ];
            
            // 停车统计
            $parking_stats = [
                'total_parking' => Db::name('parking_records')->count(),
                'today_parking' => Db::name('parking_records')->whereTime('entry_time', 'today')->count(),
                'current_parking' => Db::name('parking_records')->where('exit_time', 'null')->count(),
                'total_parking_revenue' => Db::name('parking_records')->sum('parking_fee') ?: 0
            ];
            
            $result = [
                'user_stats' => $user_stats,
                'order_stats' => $order_stats,
                'parking_stats' => $parking_stats
            ];
            
            return $this->renderSuccess($result);
        } catch (Exception $e) {
            return $this->renderError('获取系统统计失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取完整URL
     */
    private function getFullUrl($path)
    {
        if (empty($path)) {
            return '';
        }
        
        if (strpos($path, 'http') === 0) {
            return $path;
        }
        
        return request()->domain() . $path;
    }
}